package com.achieve.mqtt.handler;

import com.achieve.mqtt.service.TbLampService;
import com.achieve.mqtt.service.TbLampStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

@Component
public class ReceiverMessageHandler implements MessageHandler {

    @Autowired
    private TbLampService tbLampService;
    @Autowired
    private TbLampStatusService tbLampStatusService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        String payload = message.getPayload().toString();
        MessageHeaders headers = message.getHeaders();
        Object topicName = headers.get("mqtt_receivedTopic").toString();
        System.out.println(payload);
        System.out.println(message);
        System.out.println(topicName);
        if ("iot/lamp/line".equals(topicName)) {
            tbLampService.updateLampOnlineStatus(payload);
        } else if ("iot/lamp/device/status".equals(topicName)) {
            tbLampStatusService.saveDeviceStatus(payload);
        }
    }
}
